// src/snake-score/snake-score.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Score } from './entities/score.entity'; // 引入 Score 实体类

@Injectable()
export class SnakeScoreService {
  constructor(
    @InjectRepository(Score)
    private scoreRepository: Repository<Score>,
  ) {}

  async addScore(username: string, score: number): Promise<Score | null> {
    // 获取当前排行榜的前10名
    const topScores = await this.getLeaderboard();

    // 如果排行榜未满10个，或者新得分超过排行榜最低分，则添加新得分
    if (
      topScores.length < 10 ||
      score > topScores[topScores.length - 1].score
    ) {
      const newScore = this.scoreRepository.create({ username, score });
      const savedScore = await this.scoreRepository.save(newScore);

      // 如果排行榜数量超过10个，移除得分最低的记录
      if (topScores.length === 10) {
        const lowestScore = topScores[topScores.length - 1];
        await this.scoreRepository.delete(lowestScore.id);
      }

      return savedScore;
    } else {
      // 如果新得分没有超过排行榜最低分，则不添加
      return null;
    }
  }


  async getLeaderboard(): Promise<Score[]> {
    // 查询并排序，只返回前10名
    return this.scoreRepository.find({
      order: { score: 'DESC' }, // 按得分降序排列
      take: 10, // 只取前10名
    });
  }
}
